<script setup lang="ts">
import { getCurrentInstance, ref, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// ----
let myIndex = 0
const cateRoot = ref(null)
let cateSon = null
let cateRoots = []
let cates = []
let units = []
// ----
const tSpeed = 300
let bar = null
let clientWidth = 0
let navWidth = 0
let navSwiper = null
const navText = '全部'
const areas = ref([])
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const sliding = ref()
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const initData = () => {
  const curItems = cates.filter((item) => { return Number(item.parent_id) === Number(cateRoot.value) })
  const areaItems = []
  curItems.forEach((item, index) => {
    areaItems.push({
      value: String(item.id),
      text: proxy.$Myfun.setText(item.name)
    })
    // ----
    if (String(item.id) === String(cateSon)) myIndex = index + 1
  })
  areas.value = areaItems
}
// --initSwiperData || changeSwiperData--
const onSwiper = (swiper) => { navSwiper = swiper }
const initSwiper = (index) => {
  if (Number(areas.value.length) === 0) return false
  // --初始化--
  if (!navSwiper.el.querySelector('.bar')) {
    const newBar = document.createElement('div')
    newBar.setAttribute('class', 'bar')
    newBar.innerHTML = '<span class="xw-anim"></span>'
    navSwiper.wrapperEl.appendChild(newBar)
  }
  bar = navSwiper.el.querySelector('.bar')
  navSwiper.slides[navSwiper.activeIndex].querySelector('span').style.color = '#3388ff'
  // --Nav的可视宽度--
  clientWidth = navSwiper.wrapperEl.offsetWidth
  navWidth = 0
  for (let i = 0; i < navSwiper.slides.length; i++) {
    navWidth += navSwiper.slides[i].offsetWidth
  }
  // --点击slide事件--
  navSwiper.on('tap', () => {
    swiperMescroll(navSwiper.clickedIndex)
    // ----
    const newItems = []
    if (navSwiper.slides[navSwiper.clickedIndex].querySelector('span').innerText !== String(navText)) newItems.push(navSwiper.slides[navSwiper.clickedIndex].getAttribute('data-ID'))
    proxy.$Myfun.setSearchRes(proxy, newItems, ['cateSon'], (result) => { forSearch.value = result })
  })
  // ----
  setTimeout(() => { swiperMescroll(index) }, 100)
}
const swiperMescroll = (index) => {
  const clickIndex = index
  const clickSlide = navSwiper.slides[clickIndex]
  const activeSlidePosition = navSwiper.slides[clickIndex].offsetLeft

  // --释放时导航移动过渡--
  bar.style.transitionDuration = tSpeed + 'ms'
  bar.style.width = clickSlide.offsetWidth + 'px'
  bar.querySelector('span').style.width = clickSlide.querySelector('span').offsetWidth + 'px'
  bar.style.transform = 'translateX(' + activeSlidePosition + 'px)'

  // --导航居中--
  const navSlideWidth = clickSlide.offsetWidth
  // --activeSlide距左边的距离--
  const navActiveSlideLeft = navSwiper.slides[clickIndex].offsetLeft

  navSwiper.setTransition(tSpeed)
  if (navWidth > clientWidth) {
    if (navActiveSlideLeft < (clientWidth - navSlideWidth) / 2) {
      navSwiper.setTranslate(0)
    } else if (navActiveSlideLeft > navWidth - (navSlideWidth + clientWidth) / 2) {
      navSwiper.setTranslate(clientWidth - navWidth)
    } else {
      navSwiper.setTranslate((clientWidth - navSlideWidth) / 2 - navActiveSlideLeft)
    }
  }

  navSwiper.slides.forEach((current) => { current.querySelector('span').style.color = '#111111' })
  clickSlide.style.transitionDuration = tSpeed + 'ms'
  clickSlide.querySelector('span').style.color = '#3388ff'
}
// ----
const getCurrencyInfo = async (callback) => {
  // -- 获取商品分类 & 自定义计量单位 --
  const forCateData = {
    params: {
      'ProCategorySearch[dealer_id]': logUser.id,
      // --是否云仓分类--
      'ProCategorySearch[is_store]': 1,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forUnitData = {
    params: {
      'MeasuringUnitSearch[dealer_id]': logUser.id,
      // --是否云仓计量单位--
      'MeasuringUnitSearch[is_store]': 1,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('pro-category/index', forCateData),
    proxy.$Axios.get('measuring-unit/index', forUnitData)
  ]).then(proxy.$Axios.spread((cateData, unitData) => {
    // --商品分类--
    cates = cateData.items
    const cateItems = cates.filter((item) => { return Number(item.parent_id) === 0 })
    const rootItems = []
    cateItems.forEach((item, index) => {
      rootItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    cateRoots = rootItems
    // --计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    units = unitItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'proc/index',
    forData: {
      params: {
        'ProductSearch[name]': infoSch.value,
        'ProductSearch[parent_id]': cateRoot.value,
        'ProductSearch[pro_category_id]': cateSon,
        // ----
        'ProductSearch[dealer_id]': logUser.id,
        // --是否云仓商品--
        'ProductSearch[is_store]': 1,
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forTopAdvs = []
    let forFotAdvs = []
    let forAdv = ''
    await proxy.$Myfun.getJsonData(item.img_top, (resJson) => {
      forTopAdvs = resJson
      forAdv = resJson[0].image
    })
    await proxy.$Myfun.getJsonData(item.img_bot, (resJson) => { forFotAdvs = resJson })
    // ---
    let psize = [{
      name: '',
      cloudprice: '',
      price: '',
      unit: 0
    }]
    await proxy.$Myfun.getJsonData(item.price_json, (resJson) => { psize = resJson })
    // ----
    let forUnit = ''
    units.some((current) => {
      if (String(current.value) === String(psize[0].unit)) forUnit = current.text
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      image: forAdv,
      topImgs: forTopAdvs,
      fotImgs: forFotAdvs,
      cloudprice: Number(psize[0].cloudprice).toFixed(2),
      price: Number(psize[0].price).toFixed(2),
      unitTxt: forUnit,
      noteTxt: proxy.$Myfun.setText(item.proremark_id)
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getHeadFun(2)
}
// ----
const getHeadFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 0,
        forall: { show: true, text: '不限分类' },
        slideName: 'slideLeft',
        boxClass: 'SLB-box-left',
        itemId: cateRoot.value || 0,
        title: '选择分类',
        list: cateRoots,
        callback: (info) => { proxy.$Myfun.setSearchRes(proxy, [info[1]], ['cateRoot'], (result) => { forSearch.value = result }) }
      }
      proxy.$Myfun.isIndepth(sliding.value, 'open', options)
      break
    }
    case 2: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
  }
}
const setDefault = async (item) => {
  const cpdtItems = []
  const topItems = proxy.$Global.noPdt
  const topImgs = JSON.stringify(topItems)
  // ----
  const forCPdtData = {
    params: {
      'ProductSearch[cloud_storage_id]': item.id,
      // ----
      page: 1,
      PageSize: 1000000000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('proc/index', forCPdtData)
  ]).then(proxy.$Axios.spread((cpdtData) => {
    cpdtData.items.forEach((curItem, index) => {
      cpdtItems.push(curItem.id)
    })
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(cpdtItems.length) > 0) {
    const forItems = cpdtItems
    const opts = {
      forType: 'patch',
      forUrl: 'proc/update?id=',
      forData: {
        // --是否下架商品--
        is_shelf: 1,
        // --是否展示商品--
        is_show: 1,
        // ----
        img_top: topImgs,
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }
    }
    for (let i = 0; i < Number(forItems.length); i++) {
      await setSecond(forItems[i], opts)
    }
  }
}
const setSecond = async (curItem, opts) => {
  await proxy.$http[opts.forType](opts.forUrl + curItem, opts.forData).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'CloudPdtAdm', { id: item.id })
      break
    }
    case 2: {
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
            // ----
            await setDefault(item)
            // ----
            const opts = {
              region: proxy.$Global.aoss.region,
              bucket: proxy.$Global.aoss.bucket,
              accessKeyId: proxy.$Global.aoss.accessKeyId,
              accessKeySecret: proxy.$Global.aoss.accessKeySecret
            }
            if (Number(item.topImgs.length) > 0) {
              const imgArr = item.topImgs
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            if (Number(item.fotImgs.length) > 0) {
              const imgArr = item.fotImgs
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            // ----
            await proxy.$http.delete('proc/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            proxy.$Myfun.disLoading(layerLoading.value, 'close')
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, (newVal, oldVal) => {
  infoSch.value = newVal.infoSch
  // ----
  cateRoot.value = newVal.cateRoot
  cateSon = newVal.cateSon
  // ----
  if (String(newVal.cateRoot) !== String(oldVal.cateRoot)) {
    cateSon = null
    myIndex = 0
    // ----
    proxy.$Myfun.setSearchRes(proxy, [cateRoot.value, cateSon], ['cateRoot', 'cateSon'], (result) => { forSearch.value = result })
    // ----
    if (cateRoot.value) {
      initData()
      nextTick(() => { initSwiper(myIndex) })
    }
  } else {
    // --重新请求数据--
    mescroll.scrollTo(0)
    mescroll.resetUpScroll()
  }
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  infoSch.value = forSearch.value.infoSch
  // ----
  cateRoot.value = forSearch.value.cateRoot
  cateSon = forSearch.value.cateSon
})
onMounted(() => {
  getCurrencyInfo(() => {
    if (cateRoot.value) {
      initData()
      nextTick(() => { initSwiper(myIndex) })
    }
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <a class="TOP-grap TOP-L xw-flex xw-flex-center" @click="getHeadFun(1)">
          <span><em class="fa fa-network-wired xw-color-12"></em>选择分类</span>
        </a>
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <em class="far fa-search TOP-L"></em>
          <p class="xw-flex-W1"><input class="schText" type="text" placeholder="输入关键词找商品" v-model.trim="infoSch"/></p>
          <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
          <span class="TOP-btn TOP-R xw-Lfg" @click="getHeadFun(2)">搜索</span>
        </div>
      </div>
      <div class="FNV-menu" v-if="cateRoot && Number(areas.length) > 0">
        <swiper :slides-per-view="'auto'" :freeMode="true" @swiper="onSwiper">
          <swiper-slide><span class="xw-middle">{{navText}}</span></swiper-slide>
          <swiper-slide v-for="(item, index) in areas" :data-ID="item.value"><span class="xw-middle">{{item.text}}</span></swiper-slide>
        </swiper>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-goods xw-flex xw-flex-column" ref="dataList">
          <li class="xw-Tfg xw-bg-white" v-for="(item, index) in items">
            <div class="LGD-top xw-flex xw-flex-align">
              <img class="LGD-img" :src="item.image"/>
              <div class="LGD-con xw-flex-W1">
                <div class="LGD-title xw-ellipsis-2">{{item.name}}</div>
                <div class="LGD-price xw-flex xw-flex-align">
                  <span>销售价：</span>
                  <span class="xw-color-11">{{item.price}}</span>
                  <span>元</span>
                  <span v-if="item.unitTxt">/{{item.unitTxt}}</span>
                </div>
                <div class="LGD-price xw-flex xw-flex-align">
                  <span>分销价：</span>
                  <span class="xw-color-11">{{item.cloudprice}}</span>
                  <span>元</span>
                  <span v-if="item.unitTxt">/{{item.unitTxt}}</span>
                </div>
                <div class="LGD-note xw-ellipsis" v-if="item.noteTxt">{{item.noteTxt}}</div>
              </div>
            </div>
            <div class="LGD-btns xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-btn xw-WBlue" @click="getAuditFun(1, item)">修改</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(2, item)">删除</div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <sliding-view ref="sliding"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.FNV-menu { margin-top: -0.8rem; padding: 0; height: 4rem; }
.FNV-menu .swiper { height: 100%; }

/* ---- */
.list-goods li { padding: 1.2rem 1rem 0; }
.list-goods li:before { left: 1rem; right: 1rem; }
.list-goods li:nth-of-type(1):before { display: none; }
.LGD-img { margin: 0 1rem 0 0; width: 13rem; height: 13rem; }
.LGD-title { line-height: 2.5rem; font-size: 1.7rem; }
.LGD-price { line-height: 2.5rem; }
.LGD-note { margin: 0.5rem 0 0; padding: 0 0.5rem; line-height: 2.5rem; font-size: 1.2rem; color: #888888; background: #f5f5f5; }
.LGD-btns { padding: 1rem 0 1.2rem; }
</style>
